package com.lw.config;

import com.lw.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
//                .antMatchers("/hello").hasRole("USER")
                .anyRequest().authenticated()//验证所有请求
                .and()
            .formLogin()
                //如果loginPage未配置，则生成默认登录页面
                .loginPage("/login")//默认访问路径/login，可以自定义
                .permitAll()
                .and()
                .csrf().disable()//不加出现_csrf的错误情况,跳回登录页面
            .logout()
                .permitAll()
                .and()
                .rememberMe()//即浏览器关闭后保存cookie
                .rememberMeParameter("remember")
                .tokenValiditySeconds(1200)
                .userDetailsService(userDetailsService);
    }
//    @Autowired
//    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//        auth
//            .inMemoryAuthentication()
//
//        //There is no PasswordEncoder mapped for the id "null" 的解决办法
////                .passwordEncoder(new BCryptPasswordEncoder())
////                .withUser("lw").password(new BCryptPasswordEncoder().encode("123")).roles("USER")
////                .withUser("lw").password("123").roles("USER")
////                .and().passwordEncoder(new CustomPasswordEncoder())
//        ;
//    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}